package xyz.ieden.jpa.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.ieden.jpa.entity.User;
import xyz.ieden.jpa.service.IUserService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by Gavin on 2017.08.06.
 */
@RestController
@RequestMapping(value = "user")
public class UserController {

    @Autowired
    private Optional<IUserService> userService;

    @DeleteMapping(value = "", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public void deleteUserById(@RequestBody Integer id) {
        if (userService.isPresent()) {
            userService.get().deleteById(id);
        }
    }

    @PutMapping(value = "", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public User updateUser(@RequestBody User user) {
        if (userService.isPresent()) {
            User qryUser = userService.get().findOneById(user.getId());
            if (qryUser == null) {
                return null;
            }
            User retUser = userService.get().save(user);
            return retUser;
        } else {
            return null;
        }
    }

    @PostMapping(value = "", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    public User saveUser(HttpServletRequest request, @RequestBody User user) {
        if (userService.isPresent()) {
            user.setLastIp(request.getLocalAddr());
            user.setCreateDate(new Date());
            user.setLastDate(new Date());
            User qryUser = userService.get().save(user);
            return qryUser;
        } else {
            return null;
        }
    }

    @GetMapping(value = "", produces = "application/json;charset=UTF-8")
    public List<User> getUserList() {
        if (userService.isPresent()) {
            List<User> qryUserList = userService.get().findAll();
            return qryUserList;
        }
        else {
            return null;
        }
    }

    @GetMapping(value = "{id}", produces = "application/json;charset=UTF-8")
    public User getUserById(@PathVariable(value = "id") Integer id) {
        if (userService.isPresent()) {
            User qryUser = userService.get().findOneById(id);
            return qryUser;
        }
        else {
            return null;
        }
    }
}
